<template>
    <div class="exam-result-container">
        <!-- 搜索区域 -->
        <el-card class="search-card">
            <el-form :model="searchForm" inline label-width="100px">
                <!--                <el-form-item label="学生姓名">-->
                <!--                    <el-input v-model="searchForm.sname" placeholder="请输入学生姓名"/>-->
                <!--                </el-form-item>-->
                <el-form-item label="科目名称">
                    <el-input v-model="searchForm.subjectname" placeholder="请输入科目名称"/>
                </el-form-item>
                <el-form-item label="考试日期">
                    <el-date-picker
                            v-model="searchForm.start"
                            format="YYYY-MM-DD"
                            placeholder="开始日期"
                            type="date"
                            value-format="YYYY-MM-DD"
                    />
                    <span style="margin: 0 10px">-</span>
                    <el-date-picker
                            v-model="searchForm.end"
                            format="YYYY-MM-DD"
                            placeholder="结束日期"
                            type="date"
                            value-format="YYYY-MM-DD"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleSearch">搜索</el-button>
                    <el-button @click="resetSearch">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
        <!-- 学生信息展示区域 -->
        <!--        <h2>{{ student.telephone }}</h2>-->
        <el-card v-if="student" class="student-info-card">
            <div class="student-info-header">学生信息</div>
            <el-row :gutter="20">
                <el-col :span="8">
                    <div class="student-info-item">
                        <span class="label">学号:</span>
                        <span class="value">{{ student.stuno }}</span>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="student-info-item">
                        <span class="label">姓名:</span>
                        <span class="value">{{ student.sname }}</span>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="student-info-item">
                        <span class="label">性别:</span>
                        <span class="value">{{ student.sex }}</span>
                    </div>
                </el-col>
            </el-row>
            <el-row :gutter="20">
                <el-col :span="8">
                    <div class="student-info-item">
                        <span class="label">年龄:</span>
                        <span class="value">{{ student.birthday }}</span>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="student-info-item">
                        <span class="label">QQ:</span>
                        <span class="value">{{ student.qq }}</span>
                    </div>
                </el-col>
                <el-col :span="8">
                    <div class="student-info-item">
                        <span class="label">微信:</span>
                        <span class="value">{{ student.wechat }}</span>
                    </div>
                </el-col>
            </el-row>
        </el-card>
        <!-- 表格工具栏 -->
        <div class="toolbar">
            <el-button type="primary" @click="handleAdd">新增成绩</el-button>
        </div>

        <!-- 考试成绩表格 -->
        <el-table
                v-loading="loading"
                :data="tableData"
                border
                stripe
                style="width: 100%"
        >
            <el-table-column label="ID" prop="id" width="100"/>
            <el-table-column label="学生姓名" prop="sname" show-overflow-tooltip/>
            <el-table-column label="科目名称" prop="subjectname" show-overflow-tooltip/>
            <el-table-column label="成绩" prop="score" width="100"/>
            <el-table-column label="考试日期" prop="examdate" width="120">
                <template #default="{ row }">
                    {{ formatDate(row.examdate) }}
                </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column fixed="right" label="操作" width="200">
                <template #default="{ row }">
                    <el-button size="small" @click="handleEdit(row)">编辑</el-button>
                    <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页 -->
        <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[2,10, 20, 50, 100]"
                :total="pagination.total"
                class="pagination"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
        />

        <!-- 编辑/新增对话框 -->
        <el-dialog
                v-model="dialogVisible"
                :title="dialogTitle"
                width="500px"
                @close="handleDialogClose"
        >
            <el-form
                    ref="formRef"
                    :model="form"
                    :rules="rules"
                    label-width="100px"
            >
                <!-- 学生选择下拉框 -->
                <el-form-item label="学生" prop="stid">
                    <el-select
                            v-model="form.stid"
                            :loading="studentLoading"
                            :remote-method="searchStudents"
                            filterable
                            placeholder="请选择学生"
                            remote
                            @focus="() => loadStudents()"
                    >
                        <el-option
                                v-for="item in studentOptions"
                                :key="item.stuno"
                                :label="item.sname"
                                :value="item.stuno"
                        />
                    </el-select>
                </el-form-item>

                <!-- 科目选择下拉框 -->
                <el-form-item label="科目" prop="sbid">
                    <el-select
                            v-model="form.sbid"
                            :loading="subjectLoading"
                            :remote-method="searchSubjects"
                            filterable
                            placeholder="请选择科目"
                            remote
                            @focus="() => loadSubjects()"
                    >
                        <el-option
                                v-for="item in subjectOptions"
                                :key="item.id"
                                :label="item.subjectname"
                                :value="item.id"
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="成绩" prop="score">
                    <el-input v-model.number="form.score" type="number"/>
                </el-form-item>

                <el-form-item label="考试日期" prop="examdate">
                    <el-date-picker
                            v-model="form.examdate"
                            format="YYYY-MM-DD"
                            placeholder="请选择考试日期"
                            style="width: 100%"
                            type="date"
                            value-format="YYYY-MM-DD"
                    />
                </el-form-item>
            </el-form>
            <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button :loading="submitLoading" type="primary" @click="submitForm">确 定</el-button>
        </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {useRoute} from 'vue-router' // Changed from useRouter to useRoute

import {
    paging,
    getExamResult,
    addExamResult,
    updateExamResult,
    deleteExamResult
} from '@/apis/examResult'
import {paging as pagingStudents, getStudent, paging2} from '@/apis/student'
import {paging as pagingSubjects} from '@/apis/subject'

// 加载状态
const loading = ref(false)
const submitLoading = ref(false)
const studentLoading = ref(false)
const subjectLoading = ref(false)

// 表格数据
const tableData = ref([])

// 搜索表单
const searchForm = reactive({
    sname: '',
    //stuno: null,
    subjectname: '',
    start: '',
    end: ''
})

// 分页
const pagination = reactive({
    currentPage: 1,
    pageSize: 10,
    total: 0
})

// 对话框
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)

// 表单引用
const formRef = ref(null)

// 学生选项
const studentOptions = ref([])

// 科目选项
const subjectOptions = ref([])

// 表单数据
const form = reactive({
    id: 0,
    stid: null,
    sbid: null,
    score: null,
    examdate: '',
    sname: '',
    subjectname: ''
})

const route = useRoute(); // Changed from useRouter to useRoute
const stuno = ref(null);
// console.log("ssss:", route.params)
if (route.params.stuno) {
    stuno.value = route.params.stuno;
}
//searchForm.stuno = route.params.stuno;

const student = ref(null)

// 表单验证规则
const rules = {
    stid: [
        {required: true, message: '请选择学生', trigger: 'change'}
    ],
    sbid: [
        {required: true, message: '请选择科目', trigger: 'change'}
    ],
    score: [
        {required: true, message: '请输入成绩', trigger: 'blur'},
        {type: 'number', min: 0, max: 100, message: '成绩应在0-100之间', trigger: 'blur'}
    ],
    examdate: [
        {required: true, message: '请选择考试日期', trigger: 'change'}
    ]
}

// 格式化日期
const formatDate = (dateString) => {
    if (!dateString) return ''
    const date = new Date(dateString)
    return date.getFullYear() + '-' +
        String(date.getMonth() + 1).padStart(2, '0') + '-' +
        String(date.getDate()).padStart(2, '0')
}


// 加载学生数据
const loadStudents = async (pageNum = 1, pageSize = 20) => {
    studentLoading.value = true
    try {
        const res = await pagingStudents({pageNum, pageSize})
        studentOptions.value = res.data.records
    } catch (err) {
        ElMessage.error('获取学生数据失败')
    } finally {
        studentLoading.value = false
    }
}

// 搜索学生
const searchStudents = async (query) => {
    if (query !== '') {
        studentLoading.value = true
        try {
            const res = await pagingStudents({pageNum: 1, pageSize: 20, sname: query})
            studentOptions.value = res.data.records
        } catch (err) {
            ElMessage.error('搜索学生失败')
        } finally {
            studentLoading.value = false
        }
    } else {
        loadStudents()
    }
}

// 加载科目数据
const loadSubjects = async (pageNum = 1, pageSize = 20) => {
    subjectLoading.value = true
    try {
        const res = await pagingSubjects({pageNum, pageSize})
        subjectOptions.value = res.data.records
    } catch (err) {
        ElMessage.error('获取科目数据失败')
    } finally {
        subjectLoading.value = false
    }
}

// 搜索科目
const searchSubjects = async (query) => {
    if (query !== '') {
        subjectLoading.value = true
        try {
            const res = await pagingSubjects({pageNum: 1, pageSize: 20, subjectname: query})
            subjectOptions.value = res.data.records
        } catch (err) {
            ElMessage.error('搜索科目失败')
        } finally {
            subjectLoading.value = false
        }
    } else {
        loadSubjects()
    }
}

// 获取表格数据
const fetchData = async () => {
    loading.value = true

    try {
        // Only fetch student data if stuno is available
        if (stuno.value) {
            const res2 = await getStudent(stuno.value)
            student.value = res2.data
        }

        const params = {
            pageNum: pagination.currentPage,
            pageSize: pagination.pageSize,
            ...searchForm
        }

        // Only fetch exam results if stuno is available
        if (stuno.value) {
            const res = await paging2(stuno.value, params)
            tableData.value = res.data.records
            pagination.total = res.data.total
        }
    } catch (err) {
        ElMessage.error('获取数据失败: ' + (err.message || err))
    } finally {
        loading.value = false
    }
}

// 处理搜索
const handleSearch = () => {
    pagination.currentPage = 1
    fetchData()
}

// 重置搜索
const resetSearch = () => {
    Object.assign(searchForm, {
        sname: '',
        subjectname: '',
        start: '',
        end: ''
    })
    pagination.currentPage = 1
    fetchData()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
    pagination.pageSize = val
    pagination.currentPage = 1
    fetchData()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
    pagination.currentPage = val
    fetchData()
}

// 处理新增
const handleAdd = () => {
    dialogTitle.value = '新增成绩'
    isEdit.value = false
    resetForm()
    // 加载学生和科目数据
    loadStudents()
    loadSubjects()
    dialogVisible.value = true
}

// 处理编辑
const handleEdit = async (row) => {
    dialogTitle.value = '编辑成绩'
    isEdit.value = true

    // 获取考试成绩详情
    try {
        const res = await getExamResult(row.id)
        Object.assign(form, res.data)
    } catch (err) {
        ElMessage.error('获取考试成绩信息失败')
        return
    }

    // 加载学生和科目数据
    loadStudents()
    loadSubjects()

    dialogVisible.value = true
}

// 处理删除
const handleDelete = (row) => {
    ElMessageBox.confirm(
        `确定要删除 ${row.sname} 的 ${row.subjectname} 成绩记录吗？`,
        '确认删除',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }
    ).then(async () => {
        try {
            await deleteExamResult(row.id)
            ElMessage.success('删除成功')
            fetchData()
        } catch (err) {
            ElMessage.error('删除失败')
        }
    }).catch(() => {
        // 用户取消删除
    })
}

// 重置表单
const resetForm = () => {
    Object.assign(form, {
        id: 0,
        stid: null,
        sbid: null,
        score: null,
        examdate: '',
        sname: '',
        subjectname: ''
    })
}

// 处理对话框关闭
const handleDialogClose = () => {
    formRef.value?.resetFields()
}

// 提交表单
const submitForm = () => {
    formRef.value?.validate(async (valid) => {
        if (!valid) return

        submitLoading.value = true

        console.log("form...", form)

        try {
            if (isEdit.value) {
                await updateExamResult(form.id, form)
                ElMessage.success('更新成功')
            } else {
                await addExamResult(form)
                ElMessage.success('添加成功')
            }

            dialogVisible.value = false
            fetchData()
        } catch (err) {
            ElMessage.error(isEdit.value ? '更新失败' : '添加失败')
        } finally {
            submitLoading.value = false
        }
    })
}

// 初始化数据
onMounted(() => {
    //初始加载
    //alert(222)
    //alert(route.params)
    //console.log("ssss:", route.params)
    stuno.value = route.params.stuno;
    fetchData()

})
</script>

<style scoped>
.exam-result-container {
    padding: 20px;
}

.search-card {
    margin-bottom: 20px;
}

.student-info-card {
    margin-bottom: 20px;
}

.student-info-header {
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 15px;
    color: #333;
}

.student-info-item {
    margin-bottom: 10px;
}

.student-info-item .label {
    font-weight: bold;
    margin-right: 10px;
    color: #666;
}

.toolbar {
    margin-bottom: 20px;
}

.pagination {
    margin-top: 20px;
    display: flex;
    justify-content: center;
}
</style>